const mysql = require('mysql2');

// 数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '123456', // 请根据实际情况修改
  database: 'countryside_db',
  charset: 'utf8mb4',
  timezone: '+08:00'
};

// 创建连接池
const pool = mysql.createPool({
  ...dbConfig,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 获取Promise版本的连接
const promisePool = pool.promise();

// 测试数据库连接
async function testConnection() {
  try {
    const [result] = await promisePool.execute('SELECT 1 as test');
    return true;
  } catch (error) {
    return false;
  }
}

// 启用MySQL事件调度器
async function enableEventScheduler() {
  try {
    // 检查事件调度器状态
    const [status] = await promisePool.execute("SHOW VARIABLES LIKE 'event_scheduler'");
    
    if (status.length > 0 && status[0].Value === 'OFF') {
      // 启用事件调度器
      await promisePool.execute('SET GLOBAL event_scheduler = ON');
    }
    
    return true;
  } catch (error) {
    return false;
  }
}

// 初始化时测试连接和启用事件调度器
async function initializeDatabase() {
  const connectionTest = await testConnection();
  if (connectionTest) {
    await enableEventScheduler();
  }
}

// 执行初始化
initializeDatabase();

module.exports = {
  pool,
  promisePool,
  testConnection,
  enableEventScheduler
};
